<template>
  <div class="page-dataset-info">
    <!-- content block -->
    <div class="content">
      <!-- search toolbar -->
      <div class="search-bar-box">
        <a-button title="新增管理员" type="primary" @click="modalVisible = true"
          >新增管理员</a-button
        >
        <a-tooltip placement="right">
          <template slot="title">
            <span>新增管理员需要重新登录才能进行管理员操作！</span>
          </template>
          <div class="prompt-help">
            <a-icon-font type="iconbangzhu" />
          </div>
        </a-tooltip>
      </div>
      <!-- table -->
      <div class="table-box">
        <a-table
          :columns="tableColumns"
          :data-source="tableData"
          :row-key="(record) => record.id"
          :loading="loading"
          :pagination="pagination"
        >
          <a slot="operation" slot-scope="item" @click="revokePermissions(item)"
            >撤销权限</a
          >
        </a-table>
      </div>
    </div>

    <!--  新增 modal  -->
    <a-modal
      title="新增管理员"
      :visible="modalVisible"
      :confirm-loading="confirmLoading"
      :width="400"
      :mask-closable="false"
      :destroy-on-close="true"
      ok-text="确认"
      cancel-text="取消"
      centered
      @ok="handleOk"
      @cancel="cancelModal"
    >
      <span style="margin-right: 12px;">用户名:</span>
      <a-select
        placeholder="请输入用户名搜索..."
        show-search
        allow-clear
        style="width: calc(100% - 70px);"
        @search="handleSearchAddManager"
        @select="(value, option) => selectUser(value, option)"
      >
        <a-select-option
          v-for="option in memberOptionsAddManager"
          :key="option.id"
          :value="option.name"
        >
          {{ option.name }}
        </a-select-option>
      </a-select>
    </a-modal>
  </div>
</template>
<script lang="ts">
import { queryInfoByName } from '@/api/user'
import { debounce } from 'lodash'
import { Vue, Component } from 'vue-property-decorator'
import AuditStore from '@/store/modules/audit'
import UserStore from '@/store/modules/user'

@Component
export default class Manager extends Vue {
  public currentUser: any = '' // 选择的当前用户
  private loading: boolean = false // 列表 loading
  // 管理员表头
  private tableColumns = [
    {
      title: '#',
      dataIndex: 'id',
      key: 'id',
      width: '20%',
    },
    {
      title: '用户名',
      dataIndex: 'name',
      key: 'name',
      width: '30%',
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'gmtModify',
      key: 'gmtCreate',
      width: '30%',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'operation',
      scopedSlots: { customRender: 'operation' },
    },
  ]

  private pagination: any = { pageSize: 20 }
  // 数据
  public tableData: any[] = []

  public mounted() {
    this.queryTableData()
  }

  /**
   * 查询 api
   */
  public queryTableData() {
    this.loading = true
    AuditStore.adminList()
      ?.then((response: any) => {
        if (response.data.code === 100) {
          this.tableData = response.data.result
        }
      })
      .finally(() => {
        this.loading = false
      })
  }

  /**
   * 撤销权限
   */
  public revokePermissions(user: any) {
    const myself: boolean = UserStore.currentUser?.id === user.id
    if (!myself) {
      this.$confirm({
        title: `确定要撤销" ${user.name} 的管理员权限？`,
        okText: '确定',
        cancelText: '取消',
        centered: true,
        onOk: () => {
          this.confirmRevokePermissionsByUserId(user.name, user.id, 0)
        },
      })
    } else {
      this.$message.warning('不能对自己的进行撤销权限操作！')
    }
  }

  /**
   * 确认撤销权限， 添加用户为管理员
   * @param userName 用户name
   * @param userId 用户 id
   * @param role 1 添加为管理员， 0 撤销管理员
   */
  public async confirmRevokePermissionsByUserId(
    userName: string,
    userId: number | null,
    role: number
  ) {
    const parameters = {
      name: userName,
      id: userId,
      role,
    }
    AuditStore.adminSetRole(parameters)?.then((response: any) => {
      if (response.data.code === 100) {
        this.$message.success(
          `成功${role === 1 ? '增加' : '撤销'} ${userName} 的管理员权限！`
        )
        this.queryTableData()
      }
    })
  }

  /**
   * 添加管理员弹窗
   */
  public modalVisible: boolean = false // 新增管理员 modal
  public confirmLoading: boolean = false // 新增管理员 modal 确认 btn loading
  public memberOptionsAddManager: any[] = [] // 新增管理员弹窗 模糊搜索的用户
  public addManagerUserName: string = '' // 新增管理员弹窗 选择的用户 name
  public addManagerUserId: number | null = null // 新增管理员弹窗 选择的用户 id

  // 新增管理员 关键字 模糊搜索用户
  public handleSearchAddManager(searchKey: string) {
    if (searchKey.trim().length >= 2) {
      this.queryUsersByName(searchKey.trim())
    }
  }

  // 防抖
  private queryUsersByName = debounce(
    (searchKey: string) => this._handleSearch(searchKey),
    100
  )

  // 防抖 search
  public _handleSearch(searchKey: string) {
    const parameters = {
      name: searchKey,
    }
    queryInfoByName({ data: parameters })?.then((response: any) => {
      if (response.data.code === 100) {
        this.memberOptionsAddManager = response.data.result
      }
    })
  }

  // 选择要新增的用户 id
  public selectUser(name: any, option: any) {
    this.addManagerUserName = name
    this.addManagerUserId = option.data.key
  }

  /**
   * 取消
   */
  public cancelModal() {
    this.modalVisible = false
    this.addManagerUserName = ''
    this.addManagerUserId = null
    this.confirmLoading = false
  }

  /**
   * 确认新增的用户 （修改用户权限）
   */
  public async handleOk() {
    // 判断是否已经是管理员
    const index: number = this.tableData.findIndex(
      (manager: any) => manager.id === this.addManagerUserId
    )
    if (index < 0) {
      this.confirmLoading = true
      await this.confirmRevokePermissionsByUserId(
        this.addManagerUserName,
        this.addManagerUserId,
        1
      )
      this.cancelModal()
    } else {
      this.$message.warning(
        `${this.addManagerUserName} 已拥有管理员权限, 请选择其他用户！`
      )
    }
  }
}
</script>
<style lang="less" scoped>
.page-dataset-info {
  background: #f0f2f5;
  box-sizing: border-box;
  display: block;
  height: 100%;
  padding: 12px 16px;
  width: 100%;

  .content {
    background: #fff;
    box-sizing: border-box;
    display: flex;
    flex-flow: column nowrap;
    height: 100%;
    padding: 18px;
    width: 100%;
  }

  .search-bar-box {
    align-items: center;
    display: flex;
    min-height: 48px;
    padding-bottom: 18px;
    width: 100%;

    .prompt-help {
      cursor: pointer;
      font-size: 22px;
      margin-left: 12px;
    }
  }
}

.table-box {
  overflow: auto;
}
</style>
